package com.dzl.brand.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.brand.dao.WelfareBrandMapper;
import com.dzl.brand.pojo.WelfareBrand;
import com.dzl.brand.pojo.query.WelfareBrandQuery;
import com.dzl.brand.pojo.vo.WelfareBrandVo;
import com.dzl.brand.service.WelfareBrandService;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.supplier.pojo.WelfareSupplierBrand;
import com.dzl.supplier.service.WelfareSupplierBrandService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 品牌信息表(WelfareBrand)表服务实现类
 * @author caobucao
 * @since 2021-05-19 09:45:02
 */
@Service("welfareBrandService")
public class WelfareBrandServiceImpl extends BaseServiceImpl<WelfareBrand> implements WelfareBrandService {

    @Autowired
    private WelfareBrandMapper mapper;
    @Autowired
    private WelfareSupplierBrandService welfareSupplierBrandService;
    @Autowired
    private WelfareGoodsService welfareGoodsService;

    @Override
    public PageInfo<WelfareBrandVo> selectBrandVoListPage(WelfareBrandQuery query) {
        PageHelper.startPage(query);
        List<WelfareBrandVo> list = mapper.selectBrandVoList(query);
        if(EmptyUtils.isNotEmpty(list)) {
            list.forEach(vo -> {
                String img = vo.getImg();
                vo.setImg(ImageUtils.setImageSrc(img));
            });
        }
        PageInfo<WelfareBrandVo> page = new PageInfo<WelfareBrandVo>(list);
        return page;
    }

    @Override
    public List<WelfareBrand> selectAllBrandList() {
        List<WelfareBrand> list = mapper.selectAllBrandList();
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteBrand(WelfareBrand welfareBrand) {
        WelfareGoods welfareGoodsQuery = new WelfareGoods();
        welfareGoodsQuery.setStatus(CommonConstants.YES);
        welfareGoodsQuery.setBrandId(welfareBrand.getId());
        int count = welfareGoodsService.selectCount(welfareGoodsQuery);
        if(count>0){
            throw new CommonException("该品牌有关联商品，无法删除！");
        }
        WelfareSupplierBrand supplierBrand = new WelfareSupplierBrand();
        supplierBrand.setBrandId(welfareBrand.getId());
        welfareSupplierBrandService.delete(supplierBrand);
        return mapper.updateByPrimaryKeySelective(welfareBrand);
    }

}
